package No0088_merge_sorted_array

import "fmt"

func merge1(nums1 []int, m int, nums2 []int, n int) {
	h1, h2 := 0, 0
	ans := make([]int, 0, m+n)
	for {
		if h1 == m {
			ans = append(ans, nums2[h2:]...)
			break
		}
		if h2 == n {
			ans = append(ans, nums1[h1:]...)
			break
		}
		if nums1[h1] < nums2[h2] {
			ans = append(ans, nums1[h1])
			h1++
		} else {
			ans = append(ans, nums2[h2])
			h2++
		}
	}
	copy(nums1, ans)
}

func merge(nums1 []int, m int, nums2 []int, n int) {
	p1, p2, tail := m-1, n-1, m+n-1
	for p1 >= 0 || p2 >= 0 {
		var cur int
		if p1 == -1 {
			cur = nums2[p2]
			p2--
		} else if p2 == -1 {
			cur = nums1[p1]
			p1--
		} else if nums1[p1] > nums2[p2] {
			cur = nums1[p1]
			p1--
		} else {
			cur = nums2[p2]
			p2--
		}
		nums1[tail] = cur
		tail--
	}
}

func Test() {
	//nums1 := []int{1,2,3,0,0,0}
	//nums2 := []int{2,5,6}
	nums1 := []int{2, 0}
	nums2 := []int{1}
	m, n := 1, 1
	merge(nums1, m, nums2, n)
	fmt.Println(nums1)
}
